import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { User } from '../domain/user';
import { UserConfirm } from '../domain/user-confirm';
import { ApiService } from './api.service';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private api_url;
  private headers;

  constructor(private apiService: ApiService,
    private http: HttpClient) {
    this.api_url = apiService.getUrl();
    this.headers = apiService.getHeaders();
  }

  getUser(value: string): Observable<User[]> {
    return this.http.get<User[]>(this.api_url + '/users?user_name=' + value)
      .pipe(
        catchError(this.handleError('getUsers', []))
      );
  }

  getUserConfirm(id: number, password: string): Observable<UserConfirm[]> {
    return this.http.get<UserConfirm[]>(this.api_url + '/user_confirms?id=' + id + '&password='+password)
      .pipe(
        catchError(this.handleError('getUserConfirm', []))
      );
  }

  /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  // postTest(){
  
  //   var creds = "id=" + 6 + "&name=lalala";
  //   this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
  
  //   this.http.post('http://localhost:3000/he/', creds, {
  //     this.headers
  //     })
  //     .map(res => res.json())
  //     .subscribe(data => console.log(data));

  // }
  hero: Hero = {
    "id": 5,
    "name": "test"
  };

  /** POST: add a new hero to the server */
  addHero (): Observable<any> {
  return this.http.post<Hero>("http://localhost:3000/heroes", this.hero, httpOptions).pipe(
    catchError(this.handleError<Hero>('addHero'))
  );
}

}

export class Hero {
  id: number;
  name: string;
}

